package itsm.isperp.module.controller.customer;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.dialect.DialectFactory;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.utils.DateUtils;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.paging.RenderPager;
import itsm.isperp.framework.web.request.JqGridFilterRule;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.JqGridResponse;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.app.VUserAccount;
import itsm.isperp.module.dto.solr.SolrIcdIncidentDTO;
import itsm.isperp.module.dto.solr.SolrKngKnowledgeDTO;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.app.AppMessageSuccess;
import itsm.isperp.module.entity.app.AppUploadFile;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.repository.solr.SolrKngKnowledgeItemRepository;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppMessageSuccessService;
import itsm.isperp.module.service.app.AppUploadFileService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.app.UserAccountService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.serviceCatalog.SrcServiceService;
import itsm.isperp.module.service.slm.SlmServiceTargetService;
import itsm.isperp.workflow.dto.BpmTransitionLine;
import itsm.isperp.workflow.graph.Node;
import itsm.isperp.workflow.service.BpmProcessRunService;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jdbc.support.DatabaseType;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.HighlightQuery;
import org.springframework.data.solr.core.query.SimpleHighlightQuery;
import org.springframework.data.solr.core.query.SimpleStringCriteria;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-7-24
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("customer/help/incident")
public class CusHelpIncidentController {

  @Autowired
  IcdIncidentService icdIncidentService;

  @Autowired
  CusCustomerService cusCustomerService;

  @Autowired
  protected SolrKngKnowledgeItemRepository solarKngKnowledgeItemRepository;

  @Autowired
  protected AppDictService appDictService;

  @RequestMapping(value = { "newIncident" })
  public ModelAndView newIncident(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    IcdIncident icd=null;
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    mv.addObject("user", user);
    String id = req.getParameter("id");
    if (StringUtils.isNotBlank(id)) {
      icd = icdIncidentService.findOne(id);
      mv.addObject("model", icd);
    } else {
      icd = new IcdIncident();
      icd.setId(HibernateUUIDGenerator.generate());
      icd.setLinkmanPhone(user.getMobile());
      String sql="select * from cus_user_address where user_name='"+user.getUsername()+"' order by are_df desc";
      JdbcTemplate jdbcTemplate=ContextHolder.getSpringBean("jdbcTemplate");
      List<Map<String,Object>> listdf=jdbcTemplate.queryForList(sql);
      if(listdf.size()>0)
      {
        mv.addObject("listdf", listdf);
      }
      mv.addObject("model", icd);
      
    }

    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    Map<String, Object> mp = appUserService.findOneDetailByUsername(user
        .getName());
    String userDepartmentName = (String) mp
        .get("department_treenode_name_path");
    mv.addObject("userDepartmentName", userDepartmentName);
    mv.addObject("default2", "default");
    mv.addObject("newIncident", "current");
   
    try {
      ConfCiService confCiService = ContextHolder
          .getSpringBean("confCiService");
      JqGridRequest ciReq = new JqGridRequest();
      ciReq.isPageable(false);

      // 只选择类型为主体资产的资产`
      // ciReq.addFilterRule("meta1", JqGridFilterRuleOp.eq, "1");

      DataResponse<Map<String, Object>> userCis = confCiService
          .findDetailByCusUserId(user.getId(), ciReq);
      mv.addObject("userCis", userCis);
      int ciSize = userCis.size();
      mv.addObject("ciSize", ciSize);

      // mv.addObject("id", HibernateUUIDGenerator.generate());
      // mv.addObject("services", list);
      // mv.addObject("userCis", userCis);
      CusCustomer cusCustomer = cusCustomerService
          .findOne(user.getCustomerId());
      if (cusCustomer != null) {
        mv.addObject("customerName", cusCustomer.getName());
      } else {
        mv.addObject("customerName", "");
      }
      mv.setViewName("customer/help/incident/newIncident");
    } catch (Exception e) {
      mv.setViewName("customer/help/common/message");
      return mv;
    }
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");
    List<BpmTransitionLine> nextSteps=bpmProcessRunService.getNextSteps("incidentProcess", icd.getProcessId(),
        ContextHolder.getLoginUsername());
    mv.addObject("nextSteps", nextSteps);
    return mv;
  }
  

  @RequestMapping(value = { "save" })
  public ModelAndView save(IcdIncident model, HttpServletRequest req,
      RedirectAttributes redirectAttributes) throws SQLException {

    ModelAndView mv = new ModelAndView();

    String suggestion = req.getParameter("suggestion");

    AppUser user = (AppUser) ContextHolder.getLoginUser();
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    CusCustomerService cusCustomerService = ContextHolder
        .getSpringBean("cusCustomerService");
    String incidentType=req.getParameter("incidentType");
    if(incidentType.equals("需求"))
    {
      String nd="";
      String systemName = req.getParameter("systemName");
      String ddName = req.getParameter("ddName");
      String xzwt = req.getParameter("xzwt");
      String xqnr = req.getParameter("xqnr");
      nd="所属系统:"+systemName+"\n"
          +"责任担当："+ddName+"\n"
          +"现状问题："+xzwt+"\n"
          +"需求内容："+xqnr;
      model.setDescription(nd);
    }
    else
      model.setDescription(req.getParameter("description"));
    String userMobile = req.getParameter("userMobile");
    String userEmail = req.getParameter("userEmail");
    // String choseLinkMan = req.getParameter("choseLinkMan");
    String linkmanName = req.getParameter("linkmanName");
    String customerName = req.getParameter("customerName");
    String userTel = req.getParameter("userTel");

    if (StringUtils.isEmpty(model.getProcessId())) {

      List<Map<String, Object>> projects = appUserService.findUserProjects(user
          .getId());
      if (projects != null && !projects.isEmpty()) {
        model.setProjectId(projects.get(0).get("id").toString());
      }

     
      model.setCusUserId(user.getId());
      if ("VIP".equals(user.getType())) {
        model.setAreVip(true);
      }
    }
    if (this.icdIncidentService.exists(model.getId())) {
      icdIncidentService.saveOrUpdate(model, req, "are_vip");
      IcdIncident icd=icdIncidentService.findOne(model.getId());
      String nextTaskId = req.getParameter("nextTaskId");
      String nextTransitionId = req.getParameter("nextTransitionId");
      String processId = icd.getProcessId();
      String id = req.getParameter("id");

      bpmProcessRunService.gotoNextSetp(user.getUsername(), "incidentProcess",
          nextTaskId, nextTransitionId, processId, id, null, suggestion, 0);
      mv.setViewName("redirect:/customer/help/incident/myDoingIncident");

    } else {

      // 启动新流程
      AppDictService appDictService = ContextHolder
          .getSpringBean(AppDictService.class);

      // 本人
      if (user.getFullname().equals(linkmanName)) {
        model.setLinkmanName(user.getFullname());
        String userTel_ = StringUtils.isEmpty(userTel) ? "" : userTel + "/";

        model.setLinkmanPhone(userTel_ + userMobile);

        // 更新电话
        if (!StringUtils.isWhitespace(userMobile)) {
          user.setMobile(userMobile);
          if (StringUtils.isNotBlank(userEmail))
            user.setEmail(userEmail);
          if (StringUtils.isNotBlank(userTel))
            user.setTel(userTel);

          Set<String> columns = new HashSet<>();
          columns.add("mobile");
          columns.add("email");
          columns.add("tel");
          appUserService.dynamicUpdateSpecific(user, columns);
        }

      } else {
        // 1.用户存在，（用户名和单位 用户名和手机）
        AppUser user1 = appUserService.findByFullnameWithCustomerNameOrMobile(
            linkmanName, userMobile, customerName);

        if (user1 != null) {
          if (!StringUtils.isWhitespace(userMobile))
            user1.setMobile(userMobile);
          if (StringUtils.isNotBlank(userEmail))
            user1.setEmail(userEmail);
          if (StringUtils.isNotBlank(userTel))
            user1.setTel(userTel);
          if (StringUtils.isNotBlank(customerName)) {
            CusCustomer cus = cusCustomerService
                .findOneByNameOrFullname(customerName);
            if (cus != null) {
              user1.setCustomerId(cus.getId());
              user1.setCustomerName(customerName);
            }
          }

          Set<String> columns = new HashSet<>();
          columns.add("mobile");
          columns.add("email");
          columns.add("tel");
          columns.add("customer_id");
          columns.add("customer_name");
          appUserService.dynamicUpdateSpecific(user1, columns);
        } else {

          String tuserName = ContextHolder.getLoginUsername();
          AppUser us = appUserService.findByOpenid(tuserName);
          AppUser user2 = new AppUser();
          user2.setId(HibernateUUIDGenerator.generate());
          user2.setCustomerId(us.getCustomerId());
          user2.setCustomerName(customerName);
          user2.setMobile(userMobile);
          user2.setEmail(userEmail);
          user2.setTel(userTel);
          user2.setAppDepartmentId(us.getAppDepartmentId());
          user2.setEnable(true);
          user2.setAreCustomer(true);
          user2.setFullname(linkmanName);
          String userName = userMobile;
          AppUser tuser = appUserService.findByUsername(userName, "name");
          if (tuser != null) {
            String py = itsm.isperp.framework.utils.StringUtils
                .getPinYin(linkmanName);
            UserAccountService userAccountService = ContextHolder
                .getSpringBean("userAccountService");
            VUserAccount account = userAccountService.findByUsername(py, "id");
            if (account != null) {
              py = py + 1;
            }
            userName = py;

          }
          user2.setName(userName);
          user2.setGender("男");
          user2.setPassword("WP5Essdoi1Q=");
         // appUserService.saveOrUpdate(user2);

        }
        model.setLinkmanName(linkmanName);
        String userTel_ = StringUtils.isEmpty(userTel) ? "" : userTel + "/";
        String userEmailt = StringUtils.isEmpty(userEmail) ? "" : "/"
            + userEmail;

        model.setLinkmanPhone(userTel_ + userMobile + userEmailt);
      }

      model.setSource("Web");
      model.setStatus(appDictService.getInitStatus("INCIDENT_STATUS"));

      icdIncidentService.saveOrUpdate(model);

      bpmProcessRunService.startProcess(user.getUsername(), "incidentProcess",
          model.getId(), suggestion);

      mv.setViewName("redirect:/customer/help/incident/myDoingIncident");
    }

    return mv;
  }

  // 取得
  private DataResponse<IcdIncident> getIncidentList(AppUser user,
      JqGridRequest request) {

    request.addFilterRule("title", JqGridFilterRuleOp.ne, "");
    request.addFilterRule("cus_user_id", JqGridFilterRuleOp.eq, user.getId());
    request.setSort("create_date", Direction.DESC);

    return icdIncidentService.findAll(request);

  }

  /**
   * 处理中
   * 
   * @param req
   * @param redirectAttributes
   * @return
   */
  @RequestMapping(value = { "myDoingIncident" })
  public ModelAndView myDoingIncident(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {

    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    String userName=user.getUsername();

    mv.addObject("default2", "default");
    mv.addObject("myDoingIncident", "current");
    String msgSql = "SELECT are_from_customer  FROM (SELECT are_from_customer,source_id  FROM app_message_success WHERE message_type='LEAVEMSG' ";

    if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {
      msgSql += " AND ROWNUM <= 1  ORDER BY create_date DESC";
    } else {
      msgSql += "  ORDER BY create_date DESC LIMIT 1 ";

    }
    msgSql += ")t WHERE  source_id=icd_incident.id";
    String[] columns = { "id", "code", "priority_name", "icd_category_name",
        "title", "create_date", "expect_time", "status",
        " (" + msgSql + ") AS sla_status" };
    JqGridRequest request = new JqGridRequest();
    request.setSelectColumns(columns);
    request
    .setSearchString(" cus_user_id='"+user.getId()+"'");
    request.addFilterRule("status", JqGridFilterRuleOp.ne, "已关闭");

    request.setPageable(true);
    request.setRows(15);
    String pageIndex = req.getParameter("page");
    int currentPage = 1;
    if (StringUtils.isNotEmpty(pageIndex)) {
      currentPage = Integer.parseInt(pageIndex);
    }
    request.setPage(currentPage);

    DataResponse<IcdIncident> response = this.getIncidentList(user, request);

    mv.addObject("pager", RenderPager.renderHtml(req, currentPage,
        request.getPageSize(), (int) response.getTotalElements()));

    mv.addObject("incidents", response);
    mv.setViewName("customer/help/incident/myDoingIncident");
    return mv;
  }

  /**
   * 我的待审核
   * 
   * @param req
   * @param redirectAttributes
   * @return
   */
  @RequestMapping(value = { "myTodoIncident" })
  public ModelAndView myTodoIncident(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {

    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) ContextHolder.getLoginUser();

    mv.addObject("default2", "default");
    mv.addObject("myTodoIncident", "current");
    String msgSql = "SELECT are_from_customer  FROM (SELECT are_from_customer,source_id  FROM app_message_success WHERE message_type='LEAVEMSG' ";

    if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {
      msgSql += " AND ROWNUM <= 1  ORDER BY create_date DESC";
    } else {
      msgSql += "  ORDER BY create_date DESC LIMIT 1 ";

    }
    msgSql += ")t WHERE  source_id=icd_incident.id";

    String[] columns = { "id", "code", "priority_name", "title", "create_date",
        "status", "icd_category_name", "solved_date", "process_id" ," (" + msgSql + ") AS sla_status"};
    JqGridRequest request = new JqGridRequest();
    String userName=user.getUsername();
    request.setSelectColumns(columns);
    request
        .setSearchString(" process_id IN (SELECT DISTINCT  PROC_INST_ID_ FROM (SELECT  task.PROC_INST_ID_ FROM ACT_RU_TASK task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' AND task.ASSIGNEE_ = '"+userName+"'  UNION ALL "
            + " SELECT  task.PROC_INST_ID_  FROM act_ru_identitylink task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' "
            + "     AND task.USER_ID_ = '"+userName+"' AND task.type_ = 'candidate') task) and (status in('重新提交','退回'))");
    // request.addFilterRule("status", JqGridFilterRuleOp.in, "'待审核'");

    DataResponse<IcdIncident> response = this.getIncidentList(user, request);
    mv.addObject("incidents", response);
    int size=response.getSize();
    mv.addObject("countSize", size);
    mv.setViewName("customer/help/incident/myTodoIncident");
    return mv;
  }

  /**
   * 待评分
   * 
   * @param req
   * @param redirectAttributes
   * @return
   */
  @RequestMapping(value = { "myTocloseIncident" })
  public ModelAndView myTocloseIncident(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {

    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) ContextHolder.getLoginUser();

    mv.addObject("default2", "default");
    mv.addObject("myTocloseIncident", "current");

    String[] columns = { "id", "code", "priority_name", "title", "create_date",
        "status", "icd_category_name", "icd_category_name", "solved_date" };
    JqGridRequest request = new JqGridRequest();
    request.isPageable(false);
    request.setSelectColumns(columns);
    request.addFilterRule("solver_submit_time", JqGridFilterRuleOp.isnotnull,
        null);
    request.addFilterRule("are_feedback", JqGridFilterRuleOp.eq, "0");

    if (itsm.isperp.framework.data.dialect.DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {

      request.addFilterRule("trunc(sysdate)-trunc(solve_date)",
          JqGridFilterRuleOp.lt, "30");
    } else {

      request.addFilterRule("TO_DAYS(now())-TO_DAYS(solver_submit_time)",
          JqGridFilterRuleOp.lt, "30");
    }

    request.set_serarch(true);
    // request.setSearchString(" (solver_name IS NOT NULL and creator<>'sd') AND (satisfaction=0) ");
    DataResponse<IcdIncident> response = this.getIncidentList(user, request);
    mv.addObject("incidents", response);
    mv.setViewName("customer/help/incident/myTocloseIncident");
    return mv;
  }

  /**
   * 已结束的事件
   * 
   * @param req
   * @param redirectAttributes
   * @return
   */
  @RequestMapping(value = { "myIncidentClosed" })
  public ModelAndView myIncidentClosed(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) ContextHolder.getLoginUser();

    mv.addObject("default2", "default");
    mv.addObject("myIncidentClosed", "current");

    String pageIndex = req.getParameter("page");
    int currentPage = 1;
    if (StringUtils.isNotEmpty(pageIndex)) {
      currentPage = Integer.parseInt(pageIndex);
    }

    String[] columns = { "id", "code", "priority_name", "title", "create_date",
        "status", "icd_category_name", "satisfaction" ,"close_code","are_feedback"};
    JqGridRequest request = new JqGridRequest();
    request.setPageable(true);
    request.setRows(15);

    request.setPage(currentPage);

    request.setSelectColumns(columns);

    request.addFilterRule("status", JqGridFilterRuleOp.eq, "已关闭");

    String keyword = req.getParameter("txtKeyword");
    String createDateStart = req.getParameter("createDateStart");
    String createDateEnd = req.getParameter("createDateEnd");

    mv.addObject("keyword", keyword);
    mv.addObject("createDateStart", createDateStart);
    mv.addObject("createDateEnd", createDateEnd);

    if (StringUtils.isNotEmpty(createDateStart)) {
      JqGridFilterRule fr = new JqGridFilterRule("create_date",
          JqGridFilterRuleOp.ge, createDateStart);
      fr.setType(3);
      request.addFilterRule(fr);
    }
    if (StringUtils.isNotEmpty(createDateEnd)) {
      JqGridFilterRule fr = new JqGridFilterRule("create_date",
          JqGridFilterRuleOp.le, createDateEnd + " 23:59");
      fr.setType(3);
      request.addFilterRule(fr);
    }

    if (StringUtils.isNotEmpty(keyword)) {
      request.setSearchString(" (code like '%" + keyword
          + "%' or title like '%" + keyword + "' OR status like '%" + keyword
          + "%' or description like '%" + keyword + "%')");
    }

    DataResponse<IcdIncident> response = this.getIncidentList(user, request);

    mv.addObject("pager", RenderPager.renderHtml(req, currentPage,
        request.getPageSize(), (int) response.getTotalElements()));

    mv.addObject("incidents", response);
    mv.setViewName("customer/help/incident/myIncidentClosed");
    return mv;
  }

  @RequestMapping(value = { "incidentInfo" })
  public ModelAndView incidentInfo(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) ContextHolder.getLoginUser();

    String id = req.getParameter("id");
    IcdIncident entity = icdIncidentService.findOne(id);

    String descStep1 = "登记于" + DateUtils.formatDateTime(entity.getCreateDate())
        + "。";

    String unfinishClass = "list-unfinish";

    String step2 = null, step3 = null, step4 = null, step5 = null, step6 = null, descStep2 = null, descStep3 = null, descStep4 = null, descStep5 = null, descStep6 = null;

    step2 = step3 = step4 = step5 = step6 = unfinishClass;
    AppUserService appUserService = ContextHolder
        .getSpringBean(AppUserService.class);
    if (entity.getAssignDate() != null
        && StringUtils.isNotEmpty(entity.getSupporterId())) {
      step2 = "";
      String supporterId = "";
      if (entity.getSupporterId().indexOf(",") > -1) {
        supporterId = entity.getSupporterId().split(",")[0];
      } else {
        supporterId = entity.getSupporterId();
      }
      AppUser supporter = appUserService.findByUsername(supporterId);
      if (supporter != null) {
        String slmDesc = "";

        if (StringUtils.isNotEmpty(entity.getSlmId())) {

          SlmServiceTargetService slmServiceTargetService = ContextHolder
              .getSpringBean(SlmServiceTargetService.class);

          List<Map<String, Object>> slmList = slmServiceTargetService
              .findSlmServiceTargetsValue(entity.getSlmId(), entity.getId());

          for (Map<String, Object> m : slmList) {
            slmDesc += "[" + m.get("target_name") + ":" + m.get("plan_value")
                + "]  ";
          }
        }

        String phone = "";
        String tel = supporter.getTel();
        String mobile = supporter.getMobile();
        if (StringUtils.isNotBlank(mobile))
          phone += mobile + "/";
        if (StringUtils.isNotBlank(tel))
          phone += tel;

        descStep2 = "您的事件单于" + DateUtils.formatDateTime(entity.getAssignDate())
            + "分派至工程师    " + supporter.getFullname() + "(电话：" + phone + ")。"
            + slmDesc;

        step3 = step4 = step5 = step6 = unfinishClass;
      }
    }

    if (entity.getResponseDate() != null) {
      step2 = "";
      step3 = "";
      IUser responser = appUserService.findByUsername(entity.getResponserId());
      descStep3 = "工程师    "
          + (responser == null ? "" : responser.getFullname() + "(电话："
              + responser.getMobile() + ")") + " 于"
          + DateUtils.formatDateTime(entity.getResponseDate()) + "响应了您的问题。";

    }

    if (entity.getArrivalDate() != null) {
      step2 = "";
      step3 = "";
      step4 = "";
      IUser arriver = appUserService.findByUsername(entity.getArriverId());
      descStep4 = "工程师    "
          + (arriver == null ? "" : arriver.getFullname() + "(电话："
              + arriver.getMobile() + ")") + " 于"
          + DateUtils.formatDateTime(entity.getArrivalDate()) + "到达事件现场。";

    }

    if (entity.getSolvedDate() != null) {
      step2 = "";
      step3 = "";
      step4 = "";
      step5 = "";
      IUser solver = appUserService.findByUsername(entity.getSolverId());

      descStep5 = "工程师    "
          + (solver == null ? "" : solver.getFullname() + "(电话："
              + solver.getMobile() + ")") + " 于"
          + DateUtils.formatDateTime(entity.getSolvedDate()) + "解决了此问题。";

    }

    if (entity.getClosedDate() != null) {
      step2 = "";
      step3 = "";
      step4 = "";
      step5 = "";
      step6 = "";

      descStep6 = "事件单关闭于" + DateUtils.formatDateTime(entity.getClosedDate())
          + "。";
    }
    if (entity.getSupporterId() != null && !entity.getSupporterId().equals(""))
      mv.addObject("step2", step2);

    mv.addObject("step3", step3);
    mv.addObject("step4", step4);
    mv.addObject("step5", step5);
    mv.addObject("step6", step6);

    mv.addObject("descStep1", descStep1);
    if (entity.getSupporterId() != null && !entity.getSupporterId().equals(""))
      mv.addObject("descStep2", descStep2);
    mv.addObject("descStep3", descStep3);
    mv.addObject("descStep4", descStep4);
    mv.addObject("descStep5", descStep5);
    mv.addObject("descStep6", descStep6);

    mv.addObject("model", entity);

    AppUploadFileService appUploadFileService = ContextHolder
        .getSpringBean("appUploadFileService");

    DataResponse<AppUploadFile> uploadFiles = appUploadFileService
        .getBySourceId(entity.getId());
    AppMessageSuccessService appMessageSuccessService = ContextHolder
        .getSpringBean("appMessageSuccessService");

    List<AppMessageSuccess> messages = appMessageSuccessService
        .findAllLeaveMessage(entity.getId());

    appMessageSuccessService.readAllLeaveMessage(entity.getId(),
        user.getUsername());

    mv.addObject("cusUser", appUserService.findOne(entity.getCusUserId()));
    mv.addObject("uploadFiles", uploadFiles);
    mv.addObject("messages", messages);
    
    
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");
    Map<String, Object> map = bpmProcessRunService.trace(entity.getProcessId());
    mv.addAllObjects(map);
    
    JdbcTemplate jdbcTemplate = ContextHolder
        .getSpringBean("jdbcTemplate");
    String sql="update app_message_success set readed=1 where source_id='"+id+"'";
    jdbcTemplate.update(sql);
    
    mv.setViewName("customer/help/incident/incidentInfo");
    return mv;
  }

  /**
   * 故障详细
   * 
   * @param req
   * @param redirectAttributes
   * @return
   */
  @RequestMapping(value = { "incidentDispaly" })
  public ModelAndView incidentDispaly(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) ContextHolder.getLoginUser();

    String id = req.getParameter("id");
    IcdIncident model = icdIncidentService.findOne(id);
    mv.addObject("model", model);

    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    mv.addObject("cusUser", appUserService.findOne(model.getCusUserId()));

    if (StringUtils.isNotEmpty(model.getProjectId())) {
      ProjProjectService projProjectService = ContextHolder
          .getSpringBean("projProjectService");

      Map<String, Object> m = projProjectService.findOneToMap(
          model.getProjectId(), "name");

      if (m != null) {
        mv.addObject("projectName", m.get("name"));
      }
    }

    if (StringUtils.isNotEmpty(model.getServiceCategoryId())) {
      SrcServiceService srcServiceService = ContextHolder
          .getSpringBean("srcServiceService");

      Map<String, Object> m = srcServiceService.findOneToMap(
          model.getServiceCategoryId(), "name");

      if (m != null) {
        mv.addObject("serviceCatalogName", m.get("name"));
      }
    }

    AppUploadFileService appUploadFileService = ContextHolder
        .getSpringBean("appUploadFileService");
    DataResponse<AppUploadFile> uploadFiles = appUploadFileService
        .getBySourceId(model.getId());
    mv.addObject("uploadFiles", uploadFiles);

    mv.setViewName("customer/help/incident/incidentDispaly");
    return mv;
  }

  /**
   * 用户评分页面
   * 
   * @param id
   * @param req
   * @param redirectAttributes
   * @return
   */
  @RequestMapping("userSatisfaction")
  public ModelAndView userSatisfaction(String id, HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = this.incidentDispaly(req, redirectAttributes);

    mv.addObject("default2", "default");
    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");

    List<AppDict> satisfications = appDictService
        .findByType("INCIDENT_SATISFICATION");

    mv.addObject("satisfications", satisfications);
    mv.addObject("id", id);

    mv.setViewName("customer/help/incident/userSatisfaction");
    return mv;
  }

  /**
   * 保存评分，并关闭流程，进入已关闭故障界面
   * 
   * @param model
   * @param request
   * @param redirectAttributes
   * @return
   * @throws Exception
   */
  @RequestMapping("saveSatisfaction")
  public String saveSatisfaction(IcdIncident model, HttpServletRequest request,
      RedirectAttributes redirectAttributes) throws Exception {
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    model.setCloseCode("客户关闭");
    // model.setRater(user.getAccountId());
    // model.setRaterName(user.getName());
    // model.setRateTime(new Timestamp(new Date().getTime()));

    icdIncidentService.saveSatisfaction(model);
    redirectAttributes.addAttribute("ptype", "1");

    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");

    bpmProcessRunService.endProcess(user.getUsername(), model.getProcessId(),
        model.getCustomerOpinion());

    return "redirect:myIncidentClosed";
  }

  /**
   * 留言保存
   * 
   * @param id
   * @param title
   * @param content
   * @param req
   * @param redirectAttributes
   * @return
   * @throws SQLException
   */
  @RequestMapping("saveLeaveMessage")
  public String saveLeaveMessage(String id, String title, String content,
      HttpServletRequest req, RedirectAttributes redirectAttributes)
      throws SQLException {
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    AppMessageSuccessService appMessageSuccessService = ContextHolder
        .getSpringBean("appMessageSuccessService");
    appMessageSuccessService.saveLeaveMessage(user, true, id, title, content);
    redirectAttributes.addAttribute("id", id);
    redirectAttributes.addAttribute("saveLeaveMessage", "1");
    return "redirect:incidentInfo";
  }

  /*
   * 根据关键字搜索知识库（支持全文检索）
   * 
   * @para keyword 关键字
   * 
   * @advanceCondition 高级查询条件，
   */
  @RequestMapping("searchSimilarKnowByTitle")
  @ResponseBody
  public Page<SolrKngKnowledgeDTO> searchSimilarKnowByTitle(String title) {

    if (StringUtils.isEmpty(title)) {
      return null;
    }
    HighlightQuery query = new SimpleHighlightQuery(
        new Criteria("classType").is("SolrKngKnowledgeDTO"));
    StringBuilder stringBuilder = new StringBuilder();

    stringBuilder.append("status:");
    stringBuilder.append(appDictService.findLastOneByType(
        "KNOWLEDGE_ITEM_STATUS").getName());
    stringBuilder.append(" AND ( title:");
    stringBuilder.append(title);
    stringBuilder.append(" OR categoryName:");
    stringBuilder.append(title);
    stringBuilder.append(" OR contents:");
    stringBuilder.append(title);
    stringBuilder.append(" OR keyword:");
    stringBuilder.append(title);
    stringBuilder.append(")");
    String queryStr = stringBuilder.toString();

    SimpleStringCriteria c = new SimpleStringCriteria(queryStr);
    JqGridRequest req = new JqGridRequest();
    req.setFilters(null);// 清楚原有过滤条件
    req.setRows(5);
    query.addCriteria(c);
    query.setPageRequest(req);
    return solarKngKnowledgeItemRepository.searchByKeyword(query);
  }

  // 根据标题查找类似事件For前端
  @RequestMapping("searchSimilarIncidentsByTitle")
  @ResponseBody
  public JqGridResponse<SolrIcdIncidentDTO> searchSimilarIncidentsByTitle(
      String title) {

    JqGridRequest req = new JqGridRequest();
    req.setFilters(null);// 清楚原有过滤条件
    req.setRows(5);
    // 返回一个分页的数据集
    Page<SolrIcdIncidentDTO> page = icdIncidentService.searchSimilarIncidents(
        "", "", "", title, req);

    // 返回一个符合jqgrid的json数据
    return new JqGridResponse<SolrIcdIncidentDTO>(page);

  }

  // ----------------------approval-------------------------------

  @RequestMapping("approvalEdit")
  public ModelAndView approvalEdit(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView("customer/help/incident/approvalEdit");

    AppUser user = (AppUser) ContextHolder.getLoginUser();

    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");

    String id = req.getParameter("id");
    IcdIncident model = icdIncidentService.findOne(id);
    String processId = model.getProcessId();
    String processKey = req.getParameter("processKey");
    List<BpmTransitionLine> trans = bpmProcessRunService.getNextSteps(
        processKey, processId, user.getUsername());

    AppUploadFileService appUploadFileService = ContextHolder
        .getSpringBean("appUploadFileService");

    DataResponse<AppUploadFile> uploadFiles = appUploadFileService
        .getBySourceId(model.getId());

    mv.addObject("cusUser", appUserService.findOne(model.getCusUserId()));

    mv.addObject("model", model);
    mv.addObject("trans", trans);
    mv.addObject("processKey", processKey);
    mv.addObject("uploadFiles", uploadFiles);

    return mv;
  }

  // 废弃事件单
  @RequestMapping("abandonIncident")
  @ResponseBody
  public ResultMessage abandonIncident(String id) {
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    IcdIncident model = icdIncidentService.findOne(id);

    Set<String> columns = new HashSet<>();
    columns.add("close_code");
    model.setCloseCode("取消");
    icdIncidentService.dynamicUpdateSpecific(model, columns);

    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");

    try {
      bpmProcessRunService.endProcess(user.getUsername(), model.getProcessId(),
          "废弃");
      return ResultMessage.newInstance(true);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return ResultMessage.newInstance(false);

  }

  // 重新提交事件单
  @RequestMapping("reCreateIncident")
  @ResponseBody
  public ResultMessage reCreateIncident(String id) {
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    IcdIncident model = icdIncidentService.findOne(id);
    Set<String> columns = new HashSet<>();
    columns.add("close_code");
    model.setCloseCode("取消");
    icdIncidentService.dynamicUpdateSpecific(model, columns);
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");

    try {
      List<Node> listNode = bpmProcessRunService
          .getUserTaskByProcessInstanceId(model.getProcessId());
      String backActId = "";
      for (Node n : listNode) {
        if (n.getName().equals("重新提交")) {
          backActId = n.getId();
          break;
        }
      }
      if (StringUtils.isNoneBlank(backActId)) {
        bpmProcessRunService.jumpto(model.getProcessId(), backActId,
            user.getUsername(), "重新提交");
        return ResultMessage.newInstance(true, id);
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return ResultMessage.newInstance(false);

  }
  
  @RequestMapping("saveGiveSatisfaction")
  public String saveGiveSatisfaction(IcdIncident model,
      HttpServletRequest request, RedirectAttributes redirectAttributes)
      throws Exception {
    icdIncidentService.saveSatisfaction(model);
    redirectAttributes.addAttribute("id", model.getId());
    return "redirect:userGiveSatisfaction";
  }
  
  @RequestMapping("userGiveSatisfaction")
  public ModelAndView userGiveSatisfaction(String id, HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");

    IcdIncident model = icdIncidentService.findOne(id);

    mv.addObject("cusUser", appUserService.findOne(model.getCusUserId()));

    if (StringUtils.isNotEmpty(model.getProjectId())) {
      ProjProjectService projProjectService = ContextHolder
          .getSpringBean("projProjectService");

      Map<String, Object> m = projProjectService.findOneToMap(
          model.getProjectId(), "name");

      if (m != null) {
        mv.addObject("projectName", m.get("name"));
      }
    }

    if (StringUtils.isNotEmpty(model.getServiceCategoryId())) {
      SrcServiceService srcServiceService = ContextHolder
          .getSpringBean("srcServiceService");

      Map<String, Object> m = srcServiceService.findOneToMap(
          model.getServiceCategoryId(), "name");

      if (m != null) {
        mv.addObject("serviceCatalogName", m.get("name"));
      }
    }
    // 日期差
    int diffDay = 0;
    if (model.getSolvedDate() != null) {
      long intervalMilli = (new Date()).getTime()
          - model.getSolvedDate().getTime();
      diffDay = new Long(intervalMilli / (24 * 60 * 60 * 1000))
          .intValue();
    }
    mv.addObject("diffDay", diffDay);

    mv.addObject("model", model);
    mv.addObject("default2", "default");
    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");

    List<AppDict> satisfications = appDictService
        .findByType("INCIDENT_SATISFICATION");

    mv.addObject("satisfications", satisfications);
    mv.addObject("id", id);

    mv.setViewName("customer/help/incident/userGiveSatisfaction");
    return mv;
  }

}
